#include "Score.h"

Score::Score(int playersNumber, QWidget *parent) : QWidget(parent) {
	layout = new QVBoxLayout;
	this->playersNumber = playersNumber;
	for(int i=0; i<playersNumber; ++i) {
		lcd.append(new QLCDNumber(3));
		playerName.append(new QLabel("Player"));
		layout->addWidget(playerName[i]);
		layout->addWidget(lcd[i]);
	}
	setLayout(layout);

	setFixedWidth(100);
}

void Score::setScore(int player, int points)
{
	lcd[player-1]->display(points);
}
void Score::addPoints(int player, int points) {
	lcd[player-1]->display(lcd[player-1]->value() + points);
}

void Score::reset() {
	for(int i=0; i<playersNumber; ++i) {
		lcd[i]->display(0);
	}
}

void Score::setPlayerName(int player, QString name) {
	playerName[player-1]->setText(name);
}

void Score::addPlayer(QString name) {
	lcd.append(new QLCDNumber(3));
	playerName.append(new QLabel(name));
	layout->addWidget(playerName.last());
	layout->addWidget(lcd.last());
	playersNumber++;
}

void Score::addPlayers(QStringList name) {
	foreach (QString nick, name) {
		addPlayer(nick);
	}
}

void Score::addPlayersList(QStringList name) {
	foreach (QString nick, name) {
		if (nick.startsWith("@")) {
			nick = nick.mid(1);
			addPlayer(nick);
		}
	}
}

void Score::removePlayer(int i) {
	if (i >= 0 && i < lcd.size()) {
		qDebug() << i;
		layout->removeWidget(playerName.at(i));
		layout->removeWidget(lcd.at(i));

		delete lcd.at(i);
		delete playerName.at(i);

		playerName.remove(i);
		lcd.remove(i);

		playersNumber--;
	}
}

void Score::removePlayer(QString nick) {
	int pos = playerPos(nick);
	if (pos>=0) {
		removePlayer(pos);
	}
}

int Score::playerPos(QString nick){
	int i = 0;
	bool found = false;
	foreach (QLabel* lbl, playerName) {
		if (lbl->text()==nick) {
			found = true;
			break;
		}
		i++;
	}
	if (found) {
		return i;
	} else {
		return -1;
	}
}

void Score::removeAll() {
	for (int i = lcd.size() - 1; i >= 0; i--) {
		removePlayer(i);
	}
}
